<style lang="less">
    @import '../../styles/common.less';
    @import './goods-add.less';
</style>

<template>
    <div>
        <Row>
            <Col span="18">
                <Card>
                    <Form :label-width="80">
                        <FormItem label="商品标题" :error="articleError">
                            <Input v-model="newGoods.goodsName" @on-blur="handleGoodsNameBlur" icon="android-list"/>
                        </FormItem>
                        <div class="article-link-con">
                            <transition name="fixed-link">
                                <FormItem v-show="showLink" label="固定链接">
                                    <span>
                                        <span key="pathfixedtext">{{ fixedLink }}</span><span key="pathText" v-if="!editLink">{{ articlePath }}</span>
                                        <Input key="pathInput" v-model="articlePath" style="display:inline-block;width:auto"  v-else/>
                                    </span>
                                    <span style="float:right;">
                                        <Button :type="editPathButtonType" @click="editArticlePath">{{ editPathButtonText }}</Button>
                                    </span>
                                </FormItem>
                            </transition>
                        </div>
                    </Form>
                    <div class="margin-top-20">
                        <textarea id="articleEditor"></textarea>
                    </div>
                </Card>
            </Col>
            <Col span="6" class="padding-left-10">
                <Card>
                    <p slot="title">
                        <Icon type="paper-airplane"></Icon>
                        发布
                    </p>
                    <!-- <p class="margin-top-10">
                        <Icon type="android-time"></Icon>&nbsp;&nbsp;状&nbsp;&nbsp;&nbsp; 态：
                        <Select size="small" style="width:90px" value="草稿">
                            <Option v-for="item in articleStateList" :value="item.value" :key="item.value">{{ item.value }}</Option>
                        </Select>
                    </p>
                    <p class="margin-top-10">
                        <Icon type="eye"></Icon>&nbsp;&nbsp;公开度：&nbsp;<b>{{ Openness }}</b>
                        <Button v-show="!editOpenness" size="small" @click="handleEditOpenness" type="text">修改</Button>
                        <transition name="openness-con">
                            <div v-show="editOpenness" class="openness-radio-con">
                                <RadioGroup v-model="currentOpenness" vertical>
                                    <Radio label="公开">
                                        公开
                                        <Checkbox v-show="currentOpenness === '公开'" v-model="topArticle">在首页置顶这篇文章</Checkbox>
                                    </Radio>
                                    <Radio label="密码">
                                        密码
                                        <Input v-show="currentOpenness === '密码'" style="width:120px" size="small" placeholder="请输入密码"/>
                                    </Radio>
                                    <Radio label="私密"></Radio>
                                </RadioGroup>
                                <div>
                                    <Button type="primary" @click="handleSaveOpenness">确认</Button>
                                    <Button type="ghost" @click="cancelEditOpenness">取消</Button>
                                </div>
                            </div>
                        </transition>
                    </p>-->
                    <p class="margin-top-10">
                      <Form ref="newGoods" :model="newGoods" :label-width="80">
                        <FormItem  label="商品缩略图：" >
                                   <Upload
                                     ref="upload"
                                     :show-upload-list="false"
                                     :on-success="handleSuccessGoodsIMG"
                                     :format="['jpg','jpeg','png']"
                                     :max-size="2048"
                                     :on-format-error="handleFormatError"
                                     :on-exceeded-size="handleMaxSize"
                                     type="drag"
                                     action="http://www.bangjiat.com/oss/upImg"
                                     style="display: inline-block;width:158px;">
                                     <div style="width: 158px;height:98px;line-height: 65px;" v-if="!upGoodsIMGShow">
                                         <Icon type="camera" size="20" style="line-height: 20px;"></Icon>
                                         <p style="line-height: 0px;">上传商品缩略图</p>
                                     </div>
                                     <div style="width: 158px;height:98px;" v-if="upGoodsIMGShow">
                                         <img style="width: 100%;height: 100%;" :src="newGoods.goodsThumb">
                                     </div>
                                 </Upload>
                               </FormItem>
                        <FormItem label="市场价：">
                            <InputNumber :max="1000000" :min="1" v-model="newGoods.marketPrice"></InputNumber>
                        </FormItem>
                        <FormItem label="售价：" >
                            <InputNumber :max="1000000" :min="0" v-model="newGoods.shopPrice"></InputNumber>
                        </FormItem>
                      </Form>
                    </p>
                    <Row class="margin-top-20 publish-button-con">
                        <span class="publish-button"><Button @click="handlePreview">预览</Button></span>
                        <!-- <span class="publish-button"><Button @click="handleSaveDraft">保存草稿</Button></span> -->
                        <span class="publish-button"><Button @click="handlePublish" :loading="publishLoading" icon="ios-checkmark" style="width:90px;" type="primary">新增</Button></span>
                    </Row>
                </Card>
                <div class="margin-top-10">
                    <Card>
                        <p slot="title">
                            <Icon type="navicon-round"></Icon>
                            分类
                        </p>
                        <Tabs type="card">
                            <TabPane label="所有分类">
                                <div class="classification-con">
                                    <Tree :data="catsList" @on-select-change="selectCats"></Tree>
                                </div>
                            </TabPane>
                        </Tabs>
                    </Card>
                </div>
                <div class="margin-top-10">
                    <Card>
                        <p slot="title">
                            <Icon type="ios-pricetags-outline"></Icon>
                            关键字
                        </p>
                        <Row>
                            <Col span="18">
                                <Select v-model="articleTagSelected" multiple @on-change="handleSelectTag" placeholder="请选择商品关键字">
                                    <Option v-for="item in articleTagList" :value="item.value" :key="item.value">{{ item.value }}</Option>
                                </Select>
                            </Col>
                            <Col span="6" class="padding-left-10">
                                <Button v-show="!addingNewTag" @click="handleAddNewTag" long type="ghost">新建</Button>
                            </Col>
                        </Row>
                        <transition name="add-new-tag">
                            <div v-show="addingNewTag" class="add-new-tag-con">
                                <Col span="14">
                                    <Input v-model="newTagName" placeholder="请输入关键字" />
                                </Col>
                                <Col span="5" class="padding-left-10">
                                    <Button @click="createNewTag" long type="primary">确定</Button>
                                </Col>
                                <Col span="5" class="padding-left-10">
                                    <Button @click="cancelCreateNewTag" long type="ghost">取消</Button>
                                </Col>
                            </div>
                        </transition>
                    </Card>
                </div>
            </Col>
        </Row>
    </div>
</template>

<script>
import tinymce from 'tinymce';
import {
  getCatsAll
} from 'api/lx/lxgoodscats/cats';
import {
  addGoods
} from 'api/lx/lxgoodscats/goods';
export default {
    name: 'artical-publish',
    data () {
        return {
            newGoods:{
              marketPrice:1,
              shopPrice:1
            },
            oldCatsData:[],
            catsList: [],
            loading:false,
            upGoodsIMGShow:false,

            articleTitle: '',
            articleError: '',
            showLink: false,
            fixedLink: '',
            articlePath: '',
            articlePathHasEdited: false,
            editLink: false,
            editPathButtonType: 'ghost',
            editPathButtonText: '编辑',
            articleStateList: [{value: '草稿'}, {value: '等待复审'}],
            editOpenness: false,
            Openness: '公开',
            currentOpenness: '公开',
            topArticle: false,
            publishTime: '',
            publishTimeType: 'immediately',
            editPublishTime: false, // 是否正在编辑发布时间
            articleTagSelected: [], // 文章选中的标签
            articleTagList: [], // 所有标签列表
            classificationList: [],
            classificationSelected: [], // 在所有分类目录中选中的目录数组
            offenUsedClass: [],
            offenUsedClassSelected: [], // 常用目录选中的目录
            classificationFinalSelected: [], // 最后实际选择的目录
            publishLoading: false,
            addingNewTag: false, // 添加新标签
            newTagName: '' // 新建标签名
        };
    },
    methods: {
        init(){
            this.loading = true;
            getCatsAll().then(data => {
              this.loading = false;
              if (data.status === 200) {
                this.oldCatsData = data.data;
                this.oldCatsData.forEach(item => {
                    item.title = item.name;
                    //item.expand = true;
                    item.children = new Array();
                });
                this.oldCatsData.forEach(item => {
                    if (item.pid != 0) {
                      this.oldCatsData.forEach(pItem => {
                          if (pItem.catId == item.pid) {
                            pItem.children.push(item);
                          }
                      });
                    }
                    if (item.pid == 0) {
                      item.disabled = true;
                      item.expand = true;
                      this.catsList.push(item);
                    }
                });
              } else {
                this.$Message.error(data.message);
              }
            }).catch(error => {
                this.$Message.error('服务器异常' + error);
            });
        },
        handleGoodsNameBlur () {
          //console.error(this.newGoods.goodsName,this.newGoods.goodsName.length);
            if (this.newGoods.goodsName != undefined && this.newGoods.goodsName.length !== 0) {
                // this.articleError = '';
                //localStorage.articleTitle = this.articleTitle; // 本地存储文章标题
                // if (!this.articlePathHasEdited) {
                //     let date = new Date();
                //     let year = date.getFullYear();
                //     let month = date.getMonth() + 1;
                //     let day = date.getDate();
                //     this.fixedLink = window.location.host + '/' + year + '/' + month + '/' + day + '/';
                //     this.articlePath = this.articleTitle;
                //     this.articlePathHasEdited = true;
                //     this.showLink = true;
                // }
            } else {
                // this.articleError = '文章标题不可为空哦';
                this.$Message.error('商品标题不可为空哦');
            }
        },
        selectCats (data) {
          if (data.length == 0) {
            this.newGoods.catId = '';
            this.newGoods.catName = '';
          }else {
            this.newGoods.catId = data[0].catId;
            this.newGoods.catName = data[0].title;
          }

        },
        handleSuccessGoodsIMG (response) {
            if (response.status === 200) {
              this.$Message.success('上传成功！');
              this.newGoods.goodsThumb = response.data;
              this.upGoodsIMGShow = true;
            } else {
              this.$Message.error(response.message);
            }
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '警告',
                desc: '文件 ' + file.name + ' 不正确, 请选择 jpg 或 png文件.'
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '警告',
                desc: '文件  ' + file.name + '过大, 不能超过 2M.'
            });
        },



        editArticlePath () {
            this.editLink = !this.editLink;
            this.editPathButtonType = this.editPathButtonType === 'ghost' ? 'success' : 'ghost';
            this.editPathButtonText = this.editPathButtonText === '编辑' ? '完成' : '编辑';
        },
        handleEditOpenness () {
            this.editOpenness = !this.editOpenness;
        },
        handleSaveOpenness () {
            this.Openness = this.currentOpenness;
            this.editOpenness = false;
        },
        cancelEditOpenness () {
            this.currentOpenness = this.Openness;
            this.editOpenness = false;
        },
        handleEditPublishTime () {
            this.editPublishTime = !this.editPublishTime;
        },
        handleSavePublishTime () {
            this.publishTimeType = 'timing';
            this.editPublishTime = false;
        },
        cancelEditPublishTime () {
            this.publishTimeType = 'immediately';
            this.editPublishTime = false;
        },
        setPublishTime (datetime) {
            this.publishTime = datetime;
        },
        setClassificationInOffen (selectedArray) {
            this.classificationFinalSelected = selectedArray;
        },
        handleAddNewTag () {
            this.addingNewTag = !this.addingNewTag;
        },
        createNewTag () {
            if (this.newTagName.length !== 0) {
                this.articleTagList.push({value: this.newTagName});
                this.addingNewTag = false;
                setTimeout(() => {
                    this.newTagName = '';
                }, 200);
            } else {
                this.$Message.error('请输入关键字名');
            }
        },
        cancelCreateNewTag () {
            this.newTagName = '';
            this.addingNewTag = false;
        },
        canPublish () {
            if (this.newGoods.goodsName == undefined || this.newGoods.goodsName.length == 0) {
                this.$Message.error('请输入商品标题');
                return false;
            } else if (this.newGoods.catId == undefined || this.newGoods.catId == '') {
              this.$Message.error('请选择商品分类');
              return false;
            } else if (this.newGoods.goodsThumb == undefined || this.newGoods.goodsThumb == '') {
              this.$Message.error('请上传商品缩略图');
              return false;
            } else {
                return true;
            }
        },
        handlePreview () {
            if (this.canPublish()) {
                if (this.publishTimeType === 'immediately') {
                    let date = new Date();
                    let year = date.getFullYear();
                    let month = date.getMonth() + 1;
                    let day = date.getDate();
                    let hour = date.getHours();
                    let minute = date.getMinutes();
                    let second = date.getSeconds();
                    localStorage.publishTime = year + ' 年 ' + month + ' 月 ' + day + ' 日 -- ' + hour + ' : ' + minute + ' : ' + second;
                    this.newGoods.ctime = year + ' 年 ' + month + ' 月 ' + day + ' 日 -- ' + hour + ' : ' + minute + ' : ' + second;
                } else {
                    localStorage.publishTime = this.publishTime; // 本地存储发布时间
                    this.newGoods.ctime = this.publishTime;
                }
                //localStorage.content = tinymce.activeEditor.getContent();
                this.newGoods.goodsDesc = tinymce.activeEditor.getContent();
                this.$router.push({
                    name: 'goodspage',
                    query: this.newGoods
                });
            }
        },
        handleSaveDraft () {
            if (!this.canPublish()) {
                //
            }
        },
        handlePublish () {
            if (this.canPublish()) {
                this.publishLoading = true;
                delete this.newGoods.ctime;
                this.newGoods.goodsDesc = tinymce.activeEditor.getContent();
                addGoods(this.newGoods).then(data => {
                  this.publishLoading = false;
                  if (data.status === 200) {
                      this.$Notice.success({
                          title: '新增成功',
                          desc: '商品《' + this.newGoods.goodsName + '》新增成功'
                      });
                  } else {
                    this.$Message.error(data.message);
                  }
                }).catch(error => {
                    this.$Message.error('服务器异常' + error);
                });
            }
        },
        handleSelectTag () {
            this.newGoods.keywords = this.articleTagSelected.join();
            //localStorage.tagsList = JSON.stringify(this.articleTagSelected); // 本地存储文章标签列表
        }
    },
    computed: {
        completeUrl () {
            let finalUrl = this.fixedLink + this.articlePath;
            localStorage.finalUrl = finalUrl; // 本地存储完整文章路径
            return finalUrl;
        }
    },
    mounted () {
        this.articleTagList = [
            {value: '食品'},
            {value: 'LX'},
            {value: '保健'},
            {value: '电器'},
            {value: '服装'}
        ];
        this.offenUsedClass = [
            {
                title: 'vue实例'
            },
            {
                title: '生命周期'
            },
            {
                title: '模板语法'
            },
            {
                title: '插值'
            },
            {
                title: '缩写'
            }
        ];
        tinymce.init({
            selector: '#articleEditor',
            branding: false,
            elementpath: false,
            height: 600,
            language: 'zh_CN.GB2312',
            menubar: 'edit insert view format table tools',
            theme: 'modern',
            plugins: [
                'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                'searchreplace visualblocks visualchars code fullscreen fullpage',
                'insertdatetime media nonbreaking save table contextmenu directionality',
                'emoticons paste textcolor colorpicker textpattern imagetools codesample'
            ],
            toolbar1: ' newnote print fullscreen preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
            autosave_interval: '20s',
            image_advtab: true,
            table_default_styles: {
                width: '100%',
                borderCollapse: 'collapse'
            }
        });
    },
    destroyed () {
        tinymce.get('articleEditor').destroy();
    },
    created() {
        this.init();
    }
};
</script>
